/**
 * Created by lijian on 2017/3/2.
 */

angular.module('app').service("basedataService",['$rootScope','$http','$q','$localStorage', function ($rootScope,$http,$q,$localStorage) {

    this.getLoginUserInfo=function () {
        var userInfo= JSON.parse($localStorage.userInfo);
        return userInfo;
    };

    /**
     * 获取组织机构列表
     * @param cb
     */
    this.buildOrgTreeSelectOption = function (rootNode) {
        var allNodes=[];
        traverseTree(rootNode, 1, function (node, level) {
            allNodes.push(node);
            node.displayName = "";
            for (var i = 1; i < level; i++) {
                node.displayName += "&nbsp;&nbsp;&nbsp;&nbsp;"
            }
            node.displayName +=node.name;
        });
        return allNodes;
    };

    this.getOrgTree=function () {
        var deferred = $q.defer();
        if(!$rootScope.orgTree){
            $http.get(serverPath("organization/tree")).success(function (data) {
                $rootScope.orgTree=data;
                deferred.resolve($rootScope.orgTree);
            });
        }else{
            deferred.resolve($rootScope.orgTree);
        }

        return deferred.promise;
    };

    /***
     * 获取自己所属于组织的组织结构树
     */
    this.getSelfMgrOrgTree=function () {
        var deferred = $q.defer();
        var userInfo=this.getLoginUserInfo();
        this.getOrgTree().then(function (result) {
            var mgrOrgId=userInfo.mgrOrgId;
            var rootNode=null;
            traverseTree(result, 1, function (node, level) {
                if(node.orgId==mgrOrgId){
                    rootNode=node;
                    deferred.resolve(rootNode);
                }
            });

            if(rootNode==null){
                deferred.reject("not find root org");
            }
        });
        return deferred.promise;
    };


    /**
     * 获取民族lookup项
     */
    this.getNations = function () {
        return $http.get(serverPath("common/lookup/nation"));
    };

    /**
     * 获取党内职务lookup项
     */
    this.partyPosition = function (cb) {
        return $http.get(serverPath("common/lookup/party_position"));
    };

    function traverseTree(tree, level, callback) {
        for (var i = 0; i < tree.length; i++) {
            var node = tree[i];
            if (callback) {
                callback(node, level);
            }

            if (node.children) {
                traverseTree(node.children, level+1, callback);
            }
        }
    }
}]);